package ldh.serialize.freemaker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;

public class FreeMaker {
	
	protected Configuration cfg = new Configuration();

	protected Logger logger = LoggerFactory.getLogger(FreeMaker.class);
	
	protected String outPath;
	
	protected String basePath;
	
	protected String fileName;

	public FreeMaker() {
		BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel fileStatics;
		try {
			fileStatics = (TemplateHashModel) staticModels.get(FreeMakerUtil.class.getName());
			cfg.setSharedVariable("util", fileStatics);
			String ftlPath = FreeMaker.class.getResource("./ftl/mapper.ftl").getPath();
			File file = new File(ftlPath);
			cfg.setDirectoryForTemplateLoading(file.getParentFile());
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			logger.error("freemaker init error!!!!!!!!!!!!1", e);
		}

	}

	public void out(String ftl, Map<Object, Object> root) {
		OutputStream out = null;
		try {
			String path = basePath + File.separator + outPath;
			check(path);
			out = new FileOutputStream(new File(path, fileName));
			Writer writer = new OutputStreamWriter(out);
			Template temp = cfg.getTemplate(ftl);
			temp.process(root, writer);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void check(String path) {
		File f = new File(path);
		while (!f.exists()) {
			f.mkdirs();
		}
	}

	public String getOutPath() {
		return outPath;
	}

	public void setOutPath(String outPath) {
		this.outPath = outPath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}
	
	
}
